/*
 * Copyright 2002-2006 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.tigris.jasmincc.implementation;

import java.util.*;
import org.tigris.jasmincc.*;
import org.tigris.jasmincc.framework.*;

/**
 * A template for parsing regular expression.
 * 
 * @author Sam Huang
 * 
 */
public abstract class RegularExpressionUserTemplate extends AbstractProduction {

	protected JavaCCModel javaccModel = null;

	protected Production regularExpressionProduction = null;

	protected Map<String, Object> cache = null;

	public void parse() throws Exception {

		NamingManager namingManager = (NamingManager) cache
				.get("namingManager");

		// lexer.setDump(false);
		tk = lexer.nexttok(false, defineKeyword());
		tk = lexer.nexttok(false, SYM_COLON, "[");
		if (tk.equals("[")) {
			tk = lexer.nexttok(false, "IGNORE_CASE");
			tk = lexer.nexttok(false, "]");
			tk = lexer.nexttok(false, SYM_COLON);
		}
		tk = lexer.nexttok(false, SYM_LEFT_BRACE);
		regularExpressionProduction.setLexer(lexer);
		do {
			regularExpressionProduction.parse();
			List<String> tokens = ((StorableProduction) regularExpressionProduction)
					.getTokens();

			tk = lexer.nexttok(false, SYM_VERTICAL_LINE, SYM_RIGHT_BRACE,
					SYM_LEFT_BRACE, SYM_COLON);
			if (tk.equals(SYM_LEFT_BRACE)) {
				tk = lexer.skipTo(SYM_LEFT_BRACE_CHAR);
				attachToJavaccModel(tokens.get(0), tokens.get(1), tk);
				tk = lexer.nexttok(false, SYM_VERTICAL_LINE, SYM_RIGHT_BRACE,
						SYM_COLON);
			} else {
				attachToJavaccModel(tokens.get(0), tokens.get(1), null);
			}
			// token name
			if (tk.equals(SYM_COLON)) {
				tk = lexer.nexttok();
				tk = lexer.nexttok(false, SYM_VERTICAL_LINE, SYM_RIGHT_BRACE);
				tk = namingManager.updateRef(tk);
			}
		} while (tk.equals(SYM_VERTICAL_LINE));
		// lexer.setDump(true);
	}

	protected abstract void setHeaders(List<String> headers);

	protected abstract String defineKeyword();

	protected abstract void attachToJavaccModel(String name, String value,
			String stmt);

	public void setRegularExpressionProduction(
			StorableProduction regularExpressionProduction) {
		this.regularExpressionProduction = regularExpressionProduction;
	}

	/**
	 * @param tokensManager
	 *            the tokensManager to set
	 */
	public void setJavaccModel(JavaCCModel javaccModel) {
		this.javaccModel = javaccModel;
	}
}
